<template>
  <view class="w-full bg-white rounded-md p-4">
    <u-tabs :list="tabList" :is-scroll="false" :current="current" @change="onTabChange"></u-tabs>
    <!-- 每个tab对应的显示内容 -->
    <view class="bg-white h-[250rpx] flex justify-center items-center flex-col" >
      <template v-if="currentTab === 'input'">
        <view class="w-full flex justify-center items-center">
          <u-input
            class="w-full"
            type="text"
            :border="true"
            v-model="antiFakeCode"
            placeholder="请输入溯源码"
            @focus="popupShowPay = true"
          ></u-input>
          <button class="w-80px h-30px bg-#1684FC flex items-center justify-center text-white text-14px ml-2 rounded" @click="handleAffirm()">确认</button>
          <!-- 键盘组件 -->
          <u-keyboard mode="number" @change="onChange" @backspace="onBackspace" v-model="popupShowPay"></u-keyboard>
        </view>
      </template>
      <template v-else>
        <image
          @click="handleAntiFakeCode()"
          :src="imageUrl"
          mode="aspectFit"
          class="w-[150rpx] h-[150rpx]"
        />
        <span class="w-full text-center text-[28rpx] text-[#B0B7C2] mt-[30rpx]">
          {{ hintTItle }}
        </span>
      </template>
    </view>
  </view>
</template>
<script setup lang="ts">
import { handleError, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import NFCUtils from '@/utils/nfc'
import uKeyboard from '@/uni_modules/vk-uview-ui/components/u-keyboard/u-keyboard.vue'
import { handleTree } from '@/utils/ruoyi'

type ValueType = number | string | string[] | number[]
const current = ref(0)
const currentTab = ref('')
const currentType = ref(0)
interface Tab {
  currentTab: string;
  [key: string]: any;
}

const props = withDefaults(defineProps<{
  modelValue: ValueType | null
  isScan?: boolean, // 扫码
  isNFC?: boolean, // NFC
  isRFID?: boolean, // RFID
  isInput?: boolean, // 手动输入
}>(), {
  modelValue: null,
  isScan: true,
  isNFC: true,
  isRFID: true,
  isInput: true,
})

const emits = defineEmits<{
  (event: 'change', value: ValueType): void,
  (event: 'update:modelValue', value: ValueType): void
}>()

// 初始化tabList
const tabAllList = ref([
  { name: 'NFC', currentTab: 'NFC', condition: 'isNFC', type: 2 },
  { name: 'RFID', currentTab: 'RFID', condition: 'isRFID', type: 4 },
  { name: '扫码', currentTab: 'scan', condition: 'isScan', type: 1 },
  { name: '手动输入', currentTab: 'input', condition: 'isInput', type: 3 },
])

// 动态生成tabList，根据props中的isScan、isNFC、isRFID、isInput决定是否显示
const tabList = computed(() => {
  return tabAllList.value.filter((item:any) => props[item.condition]).map((item:any) => ({
    name: item.name,
    currentTab: item.currentTab,
    type: item.type,
    condition: item.condition,
  }))
})


/**
 * 根据当前tab获取图片路径
 */
const imageUrl = computed(() => {
  const url = import.meta.env.VITE_APP_IMAGES_URL
  return `${url}${currentTab.value}.png`
})

/**
 * 根据当前tab获取提示标题
 */
const hintTItle = computed(() => {
  return currentTab.value === 'scan' ? '扫一扫' : '请靠近标识识别'
})

// #region NFC相关逻辑
// 读取NFC数据
async function readNfcData() {
  // 默认是0扇区，1块，每一个扇区不一样的密码
  const nfcdata = NFCUtils.readNfc(0, 1, 'FFFFFFFFFFFF')
  if (nfcdata.success) {
    // emits('update:modelValue', nfcdata.data)
    // emits('change', currentType.value)
    emits('change', nfcdata.data)
  } else {
    uni.showToast({ title: 'NFC识别失败，请检查设备重新扫描！' })
  }
}

// 开始NFC扫描
function startNFC() {
  const NFCData = NFCUtils.initNfc()
  if (NFCData) {
    readNfcData()
  } else {
    uni.showToast({ title: 'NFC初始化失败，请检查设备支持情况' })
  }
}
// #endregion

// 保证currentTab和current同步
watch(tabList, (list) => {
  if (list.length > 0) {
    current.value = 0
    currentTab.value = list[0].currentTab
    currentType.value = list[0].type
    if (currentTab.value === 'NFC') {
      startNFC()
    }
  }
}, { immediate: true })

// tab切换事件
function onTabChange(index: number) {
  current.value = index
  currentTab.value = tabList.value[index].currentTab
  currentType.value = tabList.value[index].type
  if (currentTab.value === 'NFC') {
    startNFC()
  }
}

// #region 扫码相关逻辑
/**
 * @description 扫码识别相关逻辑
 */
function startScanning() {
  uni.scanCode({
    onlyFromCamera: true,
    success: (res) => {
      console.log('扫码结果:', res.result)
      // emits('update:modelValue', res.result)
      // emits('change', currentType.value)
      emits('change', res.result)
    },
    fail: (err) => {
      console.error('扫码失败:', err)
    },
  })
}

/**
 * 图片点击事件
 */
function handleAntiFakeCode() {
  if (currentTab.value === 'scan') {
    startScanning()
  }
}

// #region 手动输入相关逻辑
const popupShowPay = ref(false)
const antiFakeCode = ref('')
// 键盘输入事件
const onChange = (val:any) => {
  antiFakeCode.value += val
}
// 键盘删除事件
const onBackspace = () => {
  if (antiFakeCode.value.length > 0) {
    antiFakeCode.value = antiFakeCode.value.substring(0, antiFakeCode.value.length - 1)
  }
}

// 确定按钮事件
function handleAffirm() {
  popupShowPay.value = false
  // emits('update:modelValue', antiFakeCode.value)
  //  emits('change', currentType.value)
  emits('change', antiFakeCode.value)
}
// #endregion

onMounted(() => {
})

onUnmounted(() => {
})
</script>

<style scoped lang="scss"></style>
